package edu.cornell.lsi;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.cornell.cs.lsi.projone.common.util.AppUtil;
import edu.cornell.cs.lsi.projone.service.SessionTableManager;

// Servlet for logout action
public class LogoutServlet extends HttpServlet {

	ServletConfig config;
	private SessionTableManager sessionTableMgr;

	@Override
	public void init(ServletConfig config) throws ServletException {

		this.config = config;
		super.init(config);
		sessionTableMgr = new SessionTableManager();
	}

	// Calls doPost method
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	// Process the request
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Cookie cookie = null;
		Cookie[] cookies = request.getCookies();
		String sessionID = null;

		// If cookie is null redirect the request to home page
		if (cookies == null) {
			// response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
			// response.setHeader("Location", "http://localhost:8080/lsi/home");
			// response.setContentType("text/html");

			RequestDispatcher dispatch = request.getRequestDispatcher("/home");
			dispatch.forward(request, response);
			return;

			// Retrieve the SessionID from cookie and remove it from Session
			// table if exists
		} else {
			cookie = cookies[0];
			String[] cookieValues = cookie.getValue().split(" ");
			sessionID = cookieValues[0];
			sessionTableMgr.removeEntry(sessionID);
			if (cookieValues.length == 2) {
				SessionTableManager.deleteSession(sessionID, null);
			} else
				SessionTableManager.deleteSession(sessionID, cookieValues[2]);
		}

		// Display the logout message

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
				+ "Transitional//EN\">\n";
		out.println(docType + "<HTML>\n"
				+ "<HEAD><TITLE>LSI Assignment 4</TITLE></HEAD>\n"
				+ "<body style=\"background-color:#E8E8E8;\">" +

				"<p style=\"font-family:times;color:red\">"
				+ "Your Session is expired..." + "</p>"
				+ "link to <a href=\"home\">homepage</a>"
				+ "<br><br> IP Addr:Port - "
				+ InetAddress.getLocalHost().getHostAddress() + ":"
				+ AppUtil.getPort() + "</BODY></HTML>");
	}

}
